package ps;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 两个线程交替打印1 0
 * 虚假唤醒不是说不运行了 而是会出现错误数据
 */
class ShareDate {
    private Integer num = 0;
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    public void add() {
        lock.lock();
        try {
            while (num != 0) {
                // 等待 不能生产
                condition.await();
            }
            System.out.print(num);
            num++;
            condition.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void mul() {
        lock.lock();
        try {
            while (num != 1) {
                condition.await();
            }
            System.out.print(num);
            num--;
            condition.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

public class ProductConsumer {
    public static void main(String[] args) {
        ShareDate shareDate = new ShareDate();
        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                shareDate.add();
            }
        }, "线程1").start();

        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                shareDate.mul();
            }
        }, "线程2").start();
    }
}

